package com.xiran.interceptor;

import com.xiran.annotation.IgnoreAuth;
import com.xiran.config.JwtProperties;
import com.xiran.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * JWT拦截器（支持忽略认证注解）
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 判断是否是方法处理
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        // 2. 检查是否有@IgnoreAuth注解，如果有则直接放行
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(IgnoreAuth.class)) {
            return true;
        }
        
        // 3. 从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getHeaderName());
        
        // 4. 处理令牌前缀
        if (token != null && token.startsWith(jwtProperties.getTokenPrefix())) {
            // 去除前缀
            token = token.substring(jwtProperties.getTokenPrefix().length());
        } else {
            // 令牌不存在或格式不正确
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"success\":false,\"message\":\"未授权访问：令牌不存在或格式错误\"}");
            return false;
        }
        
        try {
            // 5. 验证令牌
            if (jwtUtils.validateToken(token)) {
                // 6. 令牌有效，将用户信息存入请求属性中，方便后续使用
                request.setAttribute("claims", jwtUtils.getClaimsFromToken(token));
                return true;
            }
        } catch (Exception e) {
            log.error("令牌验证失败: {}", e.getMessage());
        }
        
        // 7. 令牌无效或过期
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        String message = jwtUtils.isTokenExpired(token) ? "令牌已过期" : "令牌无效";
        response.getWriter().write("{\"success\":false,\"message\":\"未授权访问：" + message + "\"}");
        return false;
    }
}
